import { defineStore } from 'pinia';
import type { Resume, ResumeTemplate, Theme } from '../types';
import { resumeService, templateService, themeService } from '../services/db';
import { v4 as uuidv4 } from 'uuid';

export const useResumeStore = defineStore('resume', {
  state: () => ({
    resumes: [] as Resume[],
    currentResume: null as Resume | null,
    templates: [] as ResumeTemplate[],
    currentTemplate: null as ResumeTemplate | null,
    themes: [] as Theme[],
    currentTheme: null as Theme | null,
    isLoading: false,
    error: null as string | null,
  }),
  
  getters: {
    getResumeById: (state) => (id: string) => {
      return state.resumes.find(resume => resume.id === id);
    },
    getTemplateById: (state) => (id: string) => {
      return state.templates.find(template => template.id === id);
    },
    getThemeById: (state) => (id: string) => {
      return state.themes.find(theme => theme.id === id);
    },
  },
  
  actions: {
    // 初始化数据
    async initialize() {
      this.isLoading = true;
      try {
        // 加载简历列表
        await this.fetchResumes();
        
        // 加载模板列表
        await this.fetchTemplates();
        
        // 加载主题列表
        await this.fetchThemes();
        
        // 初始化默认模板和主题（如果没有）
        if (this.templates.length === 0) {
          await this.initDefaultTemplates();
        }
        
        if (this.themes.length === 0) {
          await this.initDefaultThemes();
        }
        
        this.error = null;
      } catch (error) {
        this.error = '初始化数据失败';
        console.error('初始化数据失败:', error);
      } finally {
        this.isLoading = false;
      }
    },
    
    // 获取所有简历
    async fetchResumes() {
      try {
        this.resumes = await resumeService.getAllResumes();
      } catch (error) {
        console.error('获取简历列表失败:', error);
        throw error;
      }
    },
    
    // 获取单个简历
    async fetchResume(id: string) {
      try {
        const resume = await resumeService.getResume(id);
        if (resume) {
          this.currentResume = resume;
        }
        return resume;
      } catch (error) {
        console.error(`获取简历 ${id} 失败:`, error);
        throw error;
      }
    },
    
    // 创建新简历
    async createResume(resumeData: Partial<Resume>) {
      try {
        const newResume: Resume = {
          id: uuidv4(),
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
          templateId: resumeData.templateId || this.templates[0]?.id || '',
          themeId: resumeData.themeId || this.themes[0]?.id || '',
          name: resumeData.name || '未命名简历',
          basicInfo: resumeData.basicInfo || {
            id: uuidv4(),
            name: '',
            title: '',
            contact: {
              email: '',
              phone: '',
            },
          },
          education: resumeData.education || [],
          workExperience: resumeData.workExperience || [],
          projects: resumeData.projects || [],
          skills: resumeData.skills || [],
          certificates: resumeData.certificates || [],
          customSections: resumeData.customSections || {},
        };
        
        await resumeService.saveResume(newResume);
        this.resumes.push(newResume);
        this.currentResume = newResume;
        return newResume;
      } catch (error) {
        console.error('创建简历失败:', error);
        throw error;
      }
    },
    
    // 更新简历
    async updateResume(resumeData: Partial<Resume>) {
      if (!this.currentResume) return;
      
      try {
        const updatedResume: Resume = {
          ...this.currentResume,
          ...resumeData,
          updatedAt: new Date().toISOString(),
        };
        
        await resumeService.saveResume(updatedResume);
        
        // 更新本地状态
        const index = this.resumes.findIndex(r => r.id === updatedResume.id);
        if (index !== -1) {
          this.resumes[index] = updatedResume;
        }
        
        this.currentResume = updatedResume;
        return updatedResume;
      } catch (error) {
        console.error('更新简历失败:', error);
        throw error;
      }
    },
    
    // 删除简历
    async deleteResume(id: string) {
      try {
        await resumeService.deleteResume(id);
        this.resumes = this.resumes.filter(resume => resume.id !== id);
        
        if (this.currentResume?.id === id) {
          this.currentResume = null;
        }
      } catch (error) {
        console.error(`删除简历 ${id} 失败:`, error);
        throw error;
      }
    },
    
    // 获取所有模板
    async fetchTemplates() {
      try {
        this.templates = await templateService.getAllTemplates();
      } catch (error) {
        console.error('获取模板列表失败:', error);
        throw error;
      }
    },
    
    // 设置当前模板
    setCurrentTemplate(templateId: string) {
      const template = this.templates.find(t => t.id === templateId);
      if (template) {
        this.currentTemplate = template;
      }
    },
    
    // 初始化默认模板
    async initDefaultTemplates() {
      const defaultTemplates: ResumeTemplate[] = [
        {
          id: 'template-1',
          name: '经典简约',
          thumbnail: '/templates/classic.png',
          description: '简洁大方的经典布局，适合大多数求职场景',
        },
        {
          id: 'template-2',
          name: '现代专业',
          thumbnail: '/templates/modern.png',
          description: '现代感强，突出专业技能和工作经验',
        },
        {
          id: 'template-3',
          name: '创意设计',
          thumbnail: '/templates/creative.png',
          description: '富有创意的设计，适合设计、艺术等创意行业',
        },
      ];
      
      try {
        await templateService.initDefaultTemplates(defaultTemplates);
        this.templates = defaultTemplates;
        this.currentTemplate = defaultTemplates[0];
      } catch (error) {
        console.error('初始化默认模板失败:', error);
        throw error;
      }
    },
    
    // 获取所有主题
    async fetchThemes() {
      try {
        this.themes = await themeService.getAllThemes();
      } catch (error) {
        console.error('获取主题列表失败:', error);
        throw error;
      }
    },
    
    // 设置当前主题
    setCurrentTheme(themeId: string) {
      const theme = this.themes.find(t => t.id === themeId);
      if (theme) {
        this.currentTheme = theme;
        // 应用主题到全局
        document.documentElement.style.setProperty('--primary-color', theme.primaryColor);
        document.documentElement.style.setProperty('--secondary-color', theme.secondaryColor);
        document.documentElement.style.setProperty('--font-family', theme.fontFamily);
        
        // 切换暗色/亮色模式
        if (theme.isDark) {
          document.documentElement.classList.add('dark');
        } else {
          document.documentElement.classList.remove('dark');
        }
      }
    },
    
    // 初始化默认主题
    async initDefaultThemes() {
      const defaultThemes: Theme[] = [
        {
          id: 'theme-1',
          name: '经典蓝',
          primaryColor: '#1890ff',
          secondaryColor: '#096dd9',
          fontFamily: 'system-ui, sans-serif',
          isDark: false,
        },
        {
          id: 'theme-2',
          name: '优雅紫',
          primaryColor: '#722ed1',
          secondaryColor: '#531dab',
          fontFamily: 'system-ui, sans-serif',
          isDark: false,
        },
        {
          id: 'theme-3',
          name: '深邃黑',
          primaryColor: '#1f1f1f',
          secondaryColor: '#434343',
          fontFamily: 'system-ui, sans-serif',
          isDark: true,
        },
      ];
      
      try {
        await themeService.initDefaultThemes(defaultThemes);
        this.themes = defaultThemes;
        this.currentTheme = defaultThemes[0];
        this.setCurrentTheme(defaultThemes[0].id);
      } catch (error) {
        console.error('初始化默认主题失败:', error);
        throw error;
      }
    },
  },
});